<?php 
namespace app\admin\controller;

use app\common\model\trade\TradeCoinSales;
use app\common\model\trade\TradeCoinBuy;
use app\common\model\user\Users;
use app\common\model\trade\TradeCnySales;
use app\common\model\trade\TradeCnyBuy;
use app\common\model\trade\TradeMate;
use app\common\model\trade\TradeLeveraged;
use app\common\controller\Marcketline;
use app\common\model\coin\CoinUser;
use think\Exception;
use think\Db;
use app\common\model\user\UserActParam;
use app\common\controller\Finance;

class Trade extends Base
{
	/**
	 * 币币交易挂卖列表
	 * @return unknown
	 */
	public function coinSales()
	{
		$data = $this->request->post('');
		$obj = new TradeCoinSales();
		$list = $this->getList($data, $obj);
		return jsonSuccess($list);
	}
	
	/**
	 * 币币交易求购列表
	 */
	public function coinBuy()
	{
		$data = $this->request->post('');
		$obj = new TradeCoinBuy;
		$list = $this->getList($data, $obj);
		return jsonSuccess($list);
	}
	
	/**
	 * 法币交易挂卖列表
	 * @return unknown
	 */
	public function cnySales()
	{
		$data = $this->request -> post('');
		$obj = new TradeCnySales();
		$list = $this->getList($data, $obj);
		return jsonSuccess($list);
	}
	
	/**
	 * 法币交易求购列表
	 * @return unknown
	 */
	public function cnyBuy()
	{
		$data = $this->request -> post('');
		$obj = new TradeCnyBuy();
		$list = $this->getList($data, $obj);
		return jsonSuccess($list);
	}
	
	/**
	 * 匹配列表
	 * @return unknown
	 */
	public function mateList()
	{
		//获取客户端传递的数据
		$data = $this -> request ->post('');
		//初始化查询条件
		$where = [];
		if(!empty($data['sale_user'])){
			$user_id = Users::where(['user_name' => $data['sale_user']])->value('id');
			$where['sales_id'] = $user_id;
		}
		if(!empty($data['buy_user'])){
			$user_id = Users::where(['user_name' => $data['buy_user']])->value('id');
			$where['buy_id'] = $user_id;
		}
		if(!empty($data['state'])) $where['state'] = $data['state'];
		if(!empty($data['times'])) {
			$times = $data['times'];
			$times[0] = strtotime($times[0]);
			$times[1] = strtotime($times[1]);
			$where['create_time'] = ['between',$times];
		}
		$list = TradeMate::where($where)->order('state asc , id desc')->paginate();
		return jsonSuccess($list);
	}
	/**
	 * 获取数据列表
	 * @param array $data 条件对象数组
	 * @param object $obj 数据库model对象
	 * @return object
	 */
	private function getList($data,$obj)
	{
		//初始化查询条件
		$where = [];
		//重新组装查询条件
		if(!empty($data['user_name'])) {
			$user_id = Users::where(['user_name' => $data['user_name']])->value('id');
			$where['user_id'] = $user_id;
		}
		if(!empty($data['times'])) {
			$times = $data['times'];
			$times[0] = strtotime($times[0]);
			$times[1] = strtotime($times[1]);
			$where['create_time'] = ['between',$times];
		}
		$list = $obj ->where($where)-> order('id desc')->paginate()->toArray();
		foreach ($list['data'] as &$rows) {
			$rows['user_info'] = Users::get($rows['user_id']);
		}
		return $list;
	}
	
	/**
	 * 杠杆交易订单
	 * @return unknown
	 */
	public function getLeveraged()
	{
		$data = $this->request->post('');
		//初始化查询条件
		$where = [];
		if(!empty($data['user_name'])) {
			$user_id = Users::where(['user_name' => $data['user_name']])->value('id');
			$where['user_id'] =$user_id;
		}
		if(!empty($data['times'])) {
			$times = $data['times'];
			$times[0] = strtotime($times[0]);
			$times[1] = strtotime($times[1]);
			$where['create_time'] = ['between',$times];
		}
		if(!empty($data['trade_style']))$where['trade_style'] = $data['trade_style'];
		
		$list = TradeLeveraged::where($where)->order('id desc')->paginate();
		foreach ($list as &$rows) {
			$rows['user_info'] = Users::get($rows['user_id']);
		}
		return jsonSuccess($list);
	}
	
	/**
	 * 手动平仓
	 * @return unknown
	 */
	public function position()
	{
		$id = $this->request ->post('id');
		Db::startTrans();
		try {
			//获取当前订单
			$trade_order = TradeLeveraged::get($id);
			if($trade_order -> state == 0)throw new Exception('状态错误');
			//获取当前价格
			$marcke = new Marcketline();
			$close_line = $marcke->getSymbolClose($trade_order->symbol);
			//当前盈亏比例
			$rate = $trade_order->symbol == 'btcusdt' ?  100 / $trade_order -> multi : 10 / $trade_order -> multi ;
			$rate = ($close_line['close'] - $trade_order -> buy_price) / $rate;
			//如果是买入订单
			if($trade_order -> trade_style == 1) {
				$add_price = $trade_order->capital * $rate; //获取到盈亏金额
			}else {
				$add_price = -$trade_order->capital * $rate; //获取到盈亏金额
			}
			//计算返还金额
			//$res_price = $trade_order->capital + $add_price;
			//更改订单状态
			$trade_order->save(['state' => 0 ,'update_time' => time(),'real_price' => 0,'close' => $close_line['close']]);
			CoinUser::where(['user_id' => $trade_order->user_id,'coin_id' => $trade_order->quote_currency])->setInc('avalible_price',$trade_order->capital);
			CoinUser::where(['user_id' => $trade_order->user_id,'coin_id' => $trade_order->quote_currency])->setDec('freezing_price',$trade_order->capital);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('设置成功');
	}
	
	/**
	 * 设置无效单
	 * @throws Exception
	 * @return unknown
	 */
	public function noavail()
	{
		$id = $this->request ->post('id');
		Db::startTrans();
		try {
			//获取当前订单
			$trade_order = TradeLeveraged::get($id);
			if($trade_order -> state == 2)throw new Exception('状态错误');
			if($trade_order -> state == 1) {
				$real_num = $trade_order->capital + $trade_order -> fee;
				//改变用户账户状态
				CoinUser::where(['user_id' => $trade_order->user_id , 'coin_id' => $trade_order->quote_currency])
				->setDec('freezing_price',$real_num);
				CoinUser::where(['user_id' => $trade_order->user_id , 'coin_id' => $trade_order->quote_currency])
				->setInc('avalible_price',$real_num);
			}else {
				if($trade_order->trade_style == 1) {
					if($trade_order -> buy_price > $trade_order->close) {
						$real_num =  $trade_order->fee + $trade_order -> real_price;
					}else {
						$real_num =  $trade_order->fee - $trade_order -> real_price;
					}
				}else {
					if($trade_order -> buy_price > $trade_order->close) {
						$real_num =  $trade_order->fee - $trade_order -> real_price;
					}else {
						$real_num =  $trade_order->fee + $trade_order -> real_price;
					}
				}
				CoinUser::where(['user_id' => $trade_order->user_id , 'coin_id' => $trade_order->quote_currency])
				->setInc('avalible_price',$real_num);
			}
			//结算代理金额
			$this->returnAct($trade_order -> toArray());
			$trade_order->save(['state' => 2,'update_time' => 0,'close' => 0,'real_price' => 0]);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('设置成功');
	}
	
	/**
	 * 代理返回金额
	 * @param unknown $data
	 * @return boolean|number
	 */
	public function returnAct($data)
	{
		//获取代理信息
		$act_id = Users::where(['id' => $data['user_id']])->value('act_id');
		if($act_id){
			$act = Users::get($act_id);
			//获取代理配置
			$act_param = $this->getActParam($act_id);
			//初始化总金额
			$total_price = 0;
			//计算全部手续费
			$total_fee = $data['fee'] * $act_param['fee_rate'] / 100;
			//总金额
			$all_price = 0;
			if($data['state'] == 1) {
				$all_price = $total_fee;
			} else {
				if($data['trade_style'] == 1) {   //买入
					$total_price =  $data['close'] > $data['buy_price'] ? -$data['real_price'] : $data['real_price'];
				}else{  //卖出
					$total_price =  $data['close'] > $data['buy_price'] ? $data['real_price'] : -$data['real_price'];
				}
				$all_price = $total_price + $total_fee;
			}
			$finance = new Finance();
			if($all_price > 0) {
				Users::where(['id' => $act_id])->setDec('bail',$all_price);
			} else {
				Users::where(['id' => $act_id])->setInc('bail',-$all_price);
			}
		}
		
	}
	
	/**
	 * 代理配置
	 * @param unknown $user_id
	 * @return unknown
	 */
	public function getActParam($user_id)
	{
		$param = UserActParam::where(['user_id' => $user_id])->find();
		if(!$param) {
			$param = UserActParam::where(['id' => 1])->find();
		}
		return $param;
	}
	/**
	 * 业绩汇总
	 * @return unknown
	 */
	public function getTradeAll()
	{
		$start_time = strtotime(date('Y-m-d').'00:00:00');
		$end_time = strtotime(date('Y-m-d').'23:59:59');
		$data = $this->request->post(''); //获取客户端传递的数据
		//初始化查询条件
		$where_buy = ['trade_style' => 1,'close' => ['exp',Db::raw('> buy_price')],'state' => ['neq',2]];
		$where_sale = ['trade_style' => 2,'close' => ['exp',Db::raw('< buy_price')],'state' => ['neq',2]];
		$where_buy_down = ['trade_style' => 1,'close' => ['exp',Db::raw('< buy_price')],'state' => ['neq',2]];
		$where_sale_down = ['trade_style' => 2,'close' => ['exp',Db::raw('> buy_price')],'state' => ['neq',2]];
		$where_day_buy = ['create_time' => ['between',[$start_time,$end_time]],'trade_style' => 1,'close' => ['exp',Db::raw('> buy_price')],'state' => ['neq',2]];
		$where_day_buy_down = ['create_time' => ['between',[$start_time,$end_time]],'trade_style' => 1,'close' => ['exp',Db::raw('< buy_price')],'state' => ['neq',2]];
		$where_day_sale = ['create_time' => ['between',[$start_time,$end_time]],'trade_style' => 2,'close' => ['exp',Db::raw('< buy_price')],'state' => ['neq',2]];
		$where_day_sale_down = ['create_time' => ['between',[$start_time,$end_time]],'trade_style' => 2,'close' => ['exp',Db::raw('> buy_price')],'state' => ['neq',2]];
		$where_fee = ['state' => ['neq',2]];
		$where_fee_day =['create_time' => ['between',[$start_time,$end_time]],'state' => ['neq',2]];
		if(!empty($data['user_name'])) {
			$user_id = Users::where(['user_name' => $data['user_name']])->value('id');
			$where_buy['user_id'] = $user_id;
			$where_sale['user_id'] = $user_id;
			$where_buy_down['user_id'] = $user_id;
			$where_sale_down['user_id'] = $user_id;
			$where_day_buy['user_id'] = $user_id;
			$where_day_buy_down['user_id'] = $user_id;
			$where_day_sale['user_id'] = $user_id;
			$where_day_sale_down['user_id'] = $user_id;
			$where_fee['user_id'] = $user_id;
			$where_fee_day['user_id'] = $user_id;
		}
		if(!empty($data['times'])) {
			$times = $data['times'];
			$times[0] = strtotime($times[0]);
			$times[1] = strtotime($times[1]);
			$where_buy['create_time'] = ['between',$times];
			$where_sale['create_time'] = ['between',$times];
			$where_buy_down['create_time'] = ['between',$times];
			$where_sale_down['create_time'] = ['between',$times];
			$where_fee['create_time'] = ['between',$times];
		}
		//总手续费
		$fee = Db::name('trade_leveraged')->where($where_fee)->sum('fee');
		//总盈利
		$loss_up_buy = Db::name('trade_leveraged')->where($where_buy)->sum('real_price');
		$loss_up_sale = Db::name('trade_leveraged')->where($where_sale)->sum('real_price');
		$loss_up = $loss_up_buy + $loss_up_sale;
		//总亏损
		$loss_down_buy = Db::name('trade_leveraged')->where($where_buy_down)->sum('real_price');
		$loss_down_sale = Db::name('trade_leveraged')->where($where_sale_down)->sum('real_price');
		$loss_down = $loss_down_buy + $loss_down_sale;
		//今日手续费
		$fee_day = Db::name('trade_leveraged')->where($where_fee_day)->sum('fee');
		//今日盈利
		$loss_up_buy = Db::name('trade_leveraged')->where($where_day_buy)->sum('real_price');
		$loss_up_sale = Db::name('trade_leveraged')->where($where_day_sale)->sum('real_price');
		$loss_up_day = $loss_up_buy + $loss_up_sale;
		//今日亏损
		$loss_down_buy = Db::name('trade_leveraged')->where($where_day_buy_down)->sum('real_price');
		$loss_down_sale = Db::name('trade_leveraged')->where($where_day_sale_down)->sum('real_price');
		$loss_down_day = $loss_down_buy + $loss_down_sale;
		$res = [
				'all' => [
						'fee' => $fee,
						'loss_up' => $loss_up,
						'loss_down' => $loss_down
				],
				'day' => [
						'fee' => $fee_day,
						'loss_up' => $loss_up_day,
						'loss_down' => $loss_down_day
				]
		];
		return jsonSuccess($res);
	}
}